#
# Requires the DevWisdom plugin to be loaded prior to this plugin
#
module DevWisdom
  module HistoryRecordMigrationUtils
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def create_table_with_history(table_name, options)
        create_table(table_name, options){|td| yield td}
        create_changes_table(table_name)
      end

      def drop_table_with_history(table_name)
        drop_table(table_name)
        drop_history_table(table_name)
      end

      def drop_history_table(table_name)
        drop_table("#{table_name}_changes")
      end

      def create_changes_table(table_name)
        create_table("#{table_name}_changes") do |t|
          t.column("record_id", :integer, :null => false)
          t.column("change_type", :string, :limit => 1)
          t.column("field_name", :text)
          t.column("old_value", :text)
          t.column("new_value", :text)
          t.column("changed_by", :integer, :null => false)
          t.column("changed_at", :datetime)
        end

        foreign_key("#{table_name}_changes","change_type","change_types","code")
      end
    end #class methods
  end#MigrationUtils
end # module DevWisdom

ActiveRecord::Migration.send :include, DevWisdom::HistoryRecordMigrationUtils
